<template>
  <el-dialog :title="!dataForm.addressId ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
      label-width="80px">
      <el-form-item label-width="auto" label="所属用户ID" prop="userId">
        <el-input style="width: auto;" v-model="dataForm.userId" placeholder="所属用户ID"></el-input>
      </el-form-item>
      <el-form-item label-width="auto" label="收货人姓名" prop="consignee">
        <el-input style="width: auto;" v-model="dataForm.consignee" placeholder="收货人姓名"></el-input>
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="dataForm.phone" placeholder="联系电话（带国际区号）"></el-input>
      </el-form-item>

      <el-form-item label="区域地址" prop="district">
        <el-cascader style="width: 40%;" size="medium" :options="options" v-model="selectedOptions"
          @change="handleChange">
        </el-cascader>
      </el-form-item>
      <el-form-item label="详细地址" prop="detail">
        <el-input v-model="dataForm.detail" placeholder="详细地址"></el-input>
      </el-form-item>
      <el-form-item label-width="auto" label="是否默认地址" prop="isDefault">
        <!-- <el-input v-model="dataForm.isDefault" placeholder="是否默认地址"></el-input> -->
        <el-switch v-model="dataForm.isDefault" active-color="#13ce66" inactive-color="#ff4949" :active-value="1"
          :inactive-value="0">
        </el-switch>
      </el-form-item>
      <el-form-item label="创建时间" prop="createdAt">
        <el-input v-model="dataForm.createdAt" placeholder="创建时间"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>

import { regionData, codeToText } from 'element-china-area-data'


export default {
  data() {
    return {
      visible: false,
      dataForm: {
        addressId: 0,
        userId: '',
        consignee: '',
        phone: '',
        province: '',
        city: '',
        district: '',
        detail: '',
        isDefault: '',
        createdAt: ''
      },
      options: regionData,
      selectedOptions: [],
      dataRule: {
        userId: [
          { required: true, message: '所属用户ID不能为空', trigger: 'blur' }
        ],
        consignee: [
          { required: true, message: '收货人姓名不能为空', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '联系电话（带国际区号）不能为空', trigger: 'blur' }
        ],
        province: [
          { required: true, message: '省份/州不能为空', trigger: 'blur' }
        ],
        city: [
          { required: true, message: '城市不能为空', trigger: 'blur' }
        ],
        district: [
          { required: true, message: '区县不能为空', trigger: 'blur' }
        ],
        detail: [
          { required: true, message: '详细地址不能为空', trigger: 'blur' }
        ],
        isDefault: [
          { required: true, message: '是否默认地址不能为空', trigger: 'blur' }
        ],
        createdAt: [
          { required: true, message: '创建时间不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    init(id) {
      this.dataForm.addressId = id || 0
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()

        this.selectedOptions = []

        if (this.dataForm.addressId) {
          this.$http({
            url: this.$http.adornUrl(`/member/useraddress/info/${this.dataForm.addressId}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 200) {
              this.dataForm.userId = data.data.userId
              this.dataForm.consignee = data.data.consignee
              this.dataForm.phone = data.data.phone
              this.dataForm.province = data.data.province
              this.dataForm.city = data.data.city
              this.dataForm.district = data.data.district
              this.dataForm.detail = data.data.detail
              this.dataForm.isDefault = data.data.isDefault
              this.dataForm.createdAt = data.data.createdAt

              console.log(data);


              this.selectedOptions = [data.data.province, data.data.city, data.data.district]

              console.log(this.selectedOptions);

            }
          })
        }
      })
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/member/useraddress/${!this.dataForm.addressId ? 'save' : 'update'}`),
            method: 'post',
            data: this.$http.adornData({
              'addressId': this.dataForm.addressId || undefined,
              'userId': this.dataForm.userId,
              'consignee': this.dataForm.consignee,
              'phone': this.dataForm.phone,
              'province': this.dataForm.province,
              'city': this.dataForm.city,
              'district': this.dataForm.district,
              'detail': this.dataForm.detail,
              'isDefault': this.dataForm.isDefault,
              'createdAt': this.dataForm.createdAt
            })
          }).then(({ data }) => {
            if (data && data.code === 200) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    },
    //也可以这样写
    handleChange(value) {

      this.selectedOptions = value
      console.log(this.selectedOptions)

      // if (this.selectedOptions[0] != null && this.selectedOptions[1] != null) {
      //   const str = codeToText[this.selectedOptions[0]] + '/' + codeToText[this.selectedOptions[1]]
      //   console.log(str)
      // }

      this.dataForm.province = this.selectedOptions[0]
      this.dataForm.city = this.selectedOptions[1]
      this.dataForm.district = this.selectedOptions[2]
      console.log(this.dataForm);

    }
  }
}
</script>
